package com.rs.net.decoders.handlers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.rs.utils.Logger;
import com.rs.utils.Utils;

public class BackUpHandler {

	private static final BackUpHandler BU = new BackUpHandler();

	public static BackUpHandler go() {
		return BU;
	}

	public BackUpHandler() {
		if (Utils.isDev()) {
			File p = new File("./data/characters/");
			File pB = new File("./data/BU/"+getDate()+".zip");
			if (!pB.exists()) {
				try {
					zipDirectory(p, pB);
					Logger.log("Succesfully backed up all playerfiles!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				System.err.println("There is no need to back up playerfiles twice a day, my friend!");
			}
		} else {
			System.err.println("Couldn't back up playerfiles as not on VPS.");
		}
	}

	private final void zipDirectory(File f, File zf) throws IOException {
		ZipOutputStream z = new ZipOutputStream(new FileOutputStream(zf));
		zip(f, f, z);
		z.close();
	}

	private final void zip(File directory, File base, ZipOutputStream zos) throws IOException {
		File[] files = directory.listFiles();
		byte[] buffer = new byte[8192];
		int read = 0;
		for (int i = 0, n = files.length; i < n; i++) {
			if (files[i].isDirectory()) {
				zip(files[i], base, zos);
			} else {
				FileInputStream in = new FileInputStream(files[i]);
				ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
				zos.putNextEntry(entry);
				while (-1 != (read = in.read(buffer))) {
					zos.write(buffer, 0, read);
				}
				in.close();
			}
		}
	}

	private String getDate() {
		DateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
		Date date = new Date();
		String currentDate = dateFormat.format(date);
		date = null;
		dateFormat = null;
		return currentDate;
	}

}
